require 'minitest_helper'

class TestActions < MiniTest::Test
  def setup
    setup_redis
  end

  # Test .save

  def test_save
    RedisHashStore.save %w(foo bar), 1234, 'baz'
    assert_equal 1, Redis.current.keys.size
    assert Redis.current.exists('hash_store:foo:bar:12')
    assert_equal %w(1234), Redis.current.hkeys('hash_store:foo:bar:12')
    assert_equal 'baz', Redis.current.hget('hash_store:foo:bar:12', '1234')
  end

  def test_save_with_field
    RedisHashStore.save ['pelle', 123, 'fant'], 5, 'ping', 'field_name'
    assert_equal 1, Redis.current.keys.size
    assert Redis.current.exists('hash_store:pelle:123:fant:0')
    assert_equal %w(field_name), Redis.current.hkeys('hash_store:pelle:123:fant:0')
    assert_equal 'ping', Redis.current.hget('hash_store:pelle:123:fant:0', 'field_name')
  end

  # Test .get

  def test_get
    RedisHashStore.save %w(foo bar), 1234, 'baz'
    assert_equal 'baz', RedisHashStore.get(%w(foo bar), 1234)
  end

  def test_get_with_field
    RedisHashStore.save ['pelle', 123, 'fant'], 5, 'ping', 'field_name'
    # nil should be returned if we don't specify the field name
    assert_equal nil, RedisHashStore.get(['pelle', 123, 'fant'], 5)
    assert_equal 'ping', RedisHashStore.get(['pelle', 123, 'fant'], 5, 'field_name')
  end

  # Test .del

  def test_del_with_and_without_field
    RedisHashStore.save %w(foo bar), 1234, 'baz'
    assert_equal 1, Redis.current.keys.size
    RedisHashStore.del %w(foo bar), 1234, 'biz'
    assert_equal 1, Redis.current.keys.size
    RedisHashStore.del %w(foo bar), 1234
    assert_equal 0, Redis.current.keys.size
  end

  def test_del_with_regex_field
    fields = %w(
      field_name:random1
      field_name:random2
      field_name:random3
    )
    other_fields = %w(
      another_field_name:random1
      another_field_name:random2
      yet_another_field_name
      field_name_with_suffix
    )
    (fields + other_fields).each do |field|
      RedisHashStore.save %w(foo bar), 1234, 'baz', field
    end
    assert_equal 1, Redis.current.keys.size
    assert_equal (fields + other_fields), Redis.current.hkeys('hash_store:foo:bar:12')
    RedisHashStore.del %w(foo bar), 1234, /\Afield_name\b/
    assert_equal 1, Redis.current.keys.size
    assert_equal other_fields, Redis.current.hkeys('hash_store:foo:bar:12')
    RedisHashStore.del %w(foo bar), 1234, /yet_another_field_name/
    assert_equal 1, Redis.current.keys.size
    assert_equal other_fields - %w(yet_another_field_name), Redis.current.hkeys('hash_store:foo:bar:12')
  end
end
